<template>
	<div class="app-container" v-loading="loading" @contextmenu.prevent="">
		<div class="search-container  app_ny">
			<div class="div2" style="position: relative">
				<el-row :gutter="12" style="width: 100%">
					<el-col :span="4">
						<el-tree-select clearable placeholder="请选择所属公司" v-model="queryParams.cid"
							:data="baseConfigStore.newExCompanyList" :render-after-expand="false"
							:default-expand-all="true" check-strictly>
							<template v-slot:default="{node, data }">
								<treeBlock :nodeItem="node" :dataItem="data" :typeClass="0"></treeBlock>
							</template>
						</el-tree-select>
					</el-col>
					<el-col :span="3">
						<el-input v-model="queryParams.name" placeholder="请输入物品名称" clearable />
					</el-col>
					<el-col :span="3">
						<el-input v-model="queryParams.sku" placeholder="请输入物品编码" clearable />
					</el-col>
					<el-col :span="3">
						<el-input v-model="queryParams.part_no" placeholder="请输入物品料号" clearable />
					</el-col>
					<!-- 	<el-col :span="3">
					<el-input v-model="queryParams.specs"  placeholder="请输入规格型号" clearable />
				</el-col> -->
					<el-col :span="3">
						<el-input v-model="queryParams.brand" placeholder="请输入品牌" clearable />
					</el-col>
					<el-col :span="7">
						<el-button :loading="loading" type="primary" @click="handleQuery">
							<template #icon><i-ep-search /></template>查询</el-button>

						<el-button type="primary" @click="onExport()"><template
								#icon><i-ep-download /></template>导出</el-button>
					</el-col>
				</el-row>
				<FilterColumn class="filtBox" @handleRefresh="resetQuery()" :strtype="strtype"></FilterColumn>
			</div>


		</div>

		<el-card shadow="never">

			<div class="action-row">
				<el-button v-hasPerm="['wms.Goods/save']" @click="handleDo('','act_add')" type="primary" plain><template
						#icon><i-ep-plus /></template>新增</el-button>
				<el-button v-hasPerm="['wms.Goods/update']" @click="handleDo('', 'act_edit')"
					:disabled="multipleSelection.length !== 1" :type="buttonType(multipleSelection.length)"
					plain><template #icon><i-ep-edit /></template>修改</el-button>
				<el-button v-hasPerm="['wms.Goods/delete']" @click="handleDo('', 'act_del')"
					:disabled="multipleSelection.length !== 1" :type="buttonType(multipleSelection.length)"
					plain><template #icon><i-ep-delete /></template>删除</el-button>
			</div>

			

			<el-table ref="dataTableRef" v-loading="loading" :data="tableData" align="left" tooltip-effect="dark"
				:show-overflow-tooltip="true" border @cell-mouse-enter="rowMouse"
				@cell-mouse-leave="menuLineVisible=false" @selection-change="handleSelectionChange">
				<el-table-column type="selection" align="center" width="55" />
				<el-table-column type="index" label="序号" align="center" width="80" />
				<template v-for="(item,index) in cColumnsList()" :key='index'>
					<el-table-column :label="item.label" :align="item.align" :prop="item.prop" :width="item.width"
						:min-width="item.minwidth">
						<template v-if="item.prop == 'image'" #default="scope">
							<el-image style="width: 50px; height: 50px" :src="scope.row.image" :zoom-rate="1.2"
								:max-scale="7" :min-scale="0.2" :preview-src-list="[scope.row.image]" :initial-index="0"
								fit="cover" />
						</template>
					</el-table-column>
				</template>

			</el-table>
			<pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.page"
				v-model:limit="queryParams.limit" @pagination="handleQuery" />
		</el-card>
		<!-- 新增内容 -->
		<el-dialog v-model="dialogAdd.visible" :close-on-click-modal="false" :close-on-press-escape="false"
			class="elDiaLog" lock-scroll :title="dialogAdd?.title" width="1000px" @close="handleCancle">
			<div v-loading="formloading">
				<FormCreate :rule="dataRule?.rules" :option="options" v-model="formData" v-model:api="fApi">
					<template #field-cid="scope">
						<el-tree-select class="defalut-width3" placeholder="请选择所属公司" v-model="scope.rule.value"
							:data="baseConfigStore.newExCompanyList" :render-after-expand="false"
							:default-expand-all="true" check-strictly>
							<template v-slot:default="{node, data }">
								<treeBlock :nodeItem="node" :dataItem="data" :typeClass="0"></treeBlock>
							</template>
						</el-tree-select>

					</template>
					<template #field-image="scope">
						<el-upload class="avatar-uploader" action="/api/upload" :show-file-list="false" :on-success="
					(response, file, fileList) => 
					imageSuccess(response, file, fileList, 'image')" :before-upload="imageBeforUpload">
							<div v-if="scope.rule.value">
								<img :src="scope.rule.value" class="avatar" />
							</div>
							<el-icon v-else class="avatar-uploader-icon">
								<Plus />
							</el-icon>
							<template #tip>
								<div class="el-upload__tip">
									<el-text size="small" type="info">{{imageType.pageShow}}</el-text>
								</div>
							</template>
						</el-upload>
					</template>
				</FormCreate>
			</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" v-no-more-click  @click="doData(dialogAdd.status)">
						{{['act_edit'].includes(dialogAdd.status)?'修改':'确定'}}</el-button>
					<el-button @click="handleCancle">取消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>
<script setup lang="ts">
	defineOptions({
		name: "Stockroom",
		inheritAttrs: false,
	});
	import { Plus } from '@element-plus/icons-vue'
	
	import { imageType } from "@/utils/funcall";
	//导入 form-create
	import formCreate from "@form-create/element-ui";
	//获取 formCreate 组件
	const FormCreate = formCreate.$form();
	//接口地址
	import {
		useRequestAny,
		getGoodsList,
		getGoodsDel,
		getGoodsCreate,
		getGoodsFormEdit,
		getGoodsExport
	} from "@/api/wms";

	import { assign } from 'lodash';
	import { useBaseConfigStore } from "@/store/modules/baseConfig";
	import { useTableFilterStore } from "@/store/modules/tableFilter";
	const baseConfigStore = useBaseConfigStore();
	const TableFilter = useTableFilterStore();
	const strtype = ref('vmsGoods');

	// 表格标题
	const cTitles = [ "图片","名称", "编码","所属公司", "单位", "品牌", "规格型号", "物料号", "备注"];
	// 显示字段
	const sTitles = [ "图片", "名称","编码","所属公司", "品牌", "规格型号","备注"];
	// 字段属性	
	const cColumns = [
		
		{ label: "名称", prop: "name", align: "center", minwidth: 150 },
		{ label: "图片", prop: "image", align: "center", width: 80 },
		{ label: "编码", prop: "sku", align: "center", minwidth: 150 },
		{ label: "所属公司", prop: "company.name", align: "center", minwidth: 200 },
		{ label: "物料号", prop: "part_no", align: "center", minwidth: 150 },
		{ label: "单位", prop: "unit", align: "center", width: 100 },
		{ label: "品牌", prop: "brand", align: "center", minwidth: 150 },
		{ label: "规格型号", prop: "specs", align: "center", minwidth: 150 },
		{ label: "备注", prop: "mark", align: "center", minwidth: 200 }
	]
	interface TableGlobalLocal {
		[key : string] : any; // 或者更具体的类型
	}
	// 列表渲染
	function cColumnsList() {
		const ColumnsList = (TableFilter.tableGlobalLocal as TableGlobalLocal)[strtype.value + '_checklist'];
		if (ColumnsList) {
			const columnMap : any = {}; // 创建一个对象来存储cColumns中label和对象的映射  
			// 预先建立label到对象的映射  
			for (const column of cColumns) {
				columnMap[column.label] = column;
			}
			const newList = [];
			for (const label of ColumnsList) {
				// 尝试从映射中获取对象  
				const foundColumn = columnMap[label];
				if (foundColumn) {
					// 如果找到了，则添加到newList中  
					newList.push(foundColumn);
				}
			}
			return newList;
		}
		else {
			return [];
		}
	};
	// 列表-数据列初始化
	function columnsInit() {
		const dropColStr : string = strtype.value + '_dropCol';
		const checklistStr : string = strtype.value + '_checklist';
		const drop_col : any = (TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[dropColStr];
		const checklist = (TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[checklistStr];
		if (!drop_col) {
			(TableFilter.tableGlobalLocal as TableGlobalLocal)[dropColStr] = JSON.parse(JSON.stringify(cTitles));
			(TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[dropColStr] = JSON.parse(JSON.stringify(cTitles));
		}
		if (!checklist) {
			(TableFilter.tableGlobalLocal as TableGlobalLocal)[checklistStr] = JSON.parse(JSON.stringify(sTitles));
			(TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[checklistStr] = JSON.parse(JSON.stringify(sTitles));
		}
	}



	//m默认搜索字段
	const queryParamsData = {
		page: 1,
		limit: 20,
		name: "",//物品名称
		cid: "",//所属公司
		sku: "",//物品编码
		part_no: "",//物料号
		specs: "",//规格型号
		brand: ""//品牌
	}
	//搜索-字段配置
	const queryParams = reactive(JSON.parse(JSON.stringify(queryParamsData)));
	const loading = ref(false);
	const formloading = ref(false);//表单加载
	const total = ref(0);
	const tableData = ref<any>([]);
	const multipleSelection = ref<any>([]);
	const menuLineVisible = ref(true);
	const rowR = ref<any>({});

	const dialogAdd = reactive<any>({
		visible: false,   //弹窗显示or隐藏
		title: "", //弹窗标题
		status: "", //弹窗状态类型  :添加 add_art 编辑 edit_art 详情 detail_art  
		value: {}
	});
	const dataRule = ref<any>();
	const bindData = ref<any>()
	const fApi = ref<any>({});
	const formData = ref<any>({});
	const options = ref({
		//表单提交事件
		submitBtn: false,
		resetBtn: false
	});

	// 行菜单事件
	function rowMouse(row : any) {
		menuLineVisible.value = true
		rowR.value = row
	}
	// 数据多选事件
	function handleSelectionChange(val : any) {
		multipleSelection.value = val
	}
	// 操作按钮样式
	function buttonType(val : number) {
		if (val === 1) {
			return 'primary'
		} else {
			return 'info'
		}
	}
	// 操作
	function handleDo(row : any, act : string) {
		let uItem : any = {}
		dialogAdd.status = act
		switch (act) {
			case 'act_add':
				dialogAdd.visible = true;
				dialogAdd.title = "添加仓库"
				dataRule.value = JSON.parse(JSON.stringify(bindData.value));

				break
			case 'act_edit':
				dialogAdd.visible = true;
				dialogAdd.title = "编辑仓库"
				formloading.value = true;
				uItem = JSON.parse(JSON.stringify(row || multipleSelection.value[0]))
				formloading.value = true;
				getGoodsFormEdit({ id: uItem.id }).then((res) => {
					formloading.value = false;
					dataRule.value = Object.assign({}, res.data);
				}).finally(() => { })
				break
			case 'act_del':
				handleDelete(JSON.parse(JSON.stringify(row || multipleSelection.value[0])))
				break
			default:
		}
	}


	// 提交数据
	function doData(act?:string) {
		fApi.value.validate((valid, fail) => {
			if (valid === true) {
				formloading.value = true;
				var data = {
					url: dataRule.value.action,
					method: dataRule.value.method,
					data: formData.value
				}
				useRequestAny(data).then((res) => {
					ElMessage({
						message: res.msg,
						type: 'success',
					})
					formloading.value = false;
					handleQuery();
					handleCancle()
				}).finally(() => { })
			}
		})
	}


	// 重置表单内容
	function handleCancle() {
		dialogAdd.visible = false;
	}
	// 刷新页面
	function resetQuery(){
		handleQuery();
	}
	
	//获取仓库信息列表
	function handleQuery() {
		loading.value = true;
		getGoodsList(queryParams).then((res) => {
			console.log(res);
			tableData.value = res.data.list;
			total.value = res.data.count;
		}).finally(() => {
			loading.value = false;
		})
	}



	// 删除内容
	function handleDelete(row:any) {
		const Ids =row.id;
		if (!Ids) {
			ElMessage.warning("请勾选删除项");
			return;
		}
		ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
			confirmButtonText: "确定",
			cancelButtonText: "取消",
			type: "warning",
		}).then(() => {
			loading.value = true;
			getGoodsDel({
				id: Ids
			}).then((res) => {
				console.log(res)
				ElMessage({
					message: '删除成功',
					type: 'success'
				})
				handleQuery();
			}).finally(() => {
				loading.value = false;
			})
		}, function () {
			console.log('取消删除')
		})
	}

	
	
	function imageSuccess(response : any, file : any, fileList : any, ls : any) {
		console.log(response, file, fileList, ls)
		formData.value[ls] = response.data.url;
	}
	function imageBeforUpload(file : any) {
		var fileSize = file.size / 1024 / 1024 < imageType.size;
		const index = file.name.lastIndexOf(".");
		const ext = file.name.substr(index + 1).toUpperCase();
		if (imageType.extarr.indexOf(ext) == -1) {
			ElMessage({
				message: imageType.errorMes,
				type: 'error',
			})
			return false;
		}
		if (!fileSize) {
			ElMessage({
				message: imageType.prompt,
				type: 'error',
			})
			return false;
		}
		console.log('开始上传文件')
	}


	// 导出信息
	function onExport() {
		getGoodsExport(queryParams).then((response : any) => {
			const blob = new Blob([response.data], {
				type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
			});
			const a = document.createElement("a");
			const href = window.URL.createObjectURL(blob); // 下载的链接
			a.href = href;
			a.download = decodeURI(
				response.headers["content-disposition"].split(";")[1].split("=")[1]
			); // 获取后台设置的文件名称
			document.body.appendChild(a);
			a.click(); // 点击导出
			document.body.removeChild(a); // 下载完成移除元素
			window.URL.revokeObjectURL(href); // 释放掉blob对象
		});
	}


	// 获取options 配置项
	function get_options() {
		initDataForm();
	}
	// 初始化表单初始项
	function initDataForm() {
		getGoodsCreate({}).then((res) => {
			bindData.value = res.data;
		}).finally(() => { })
	}

	onMounted(() => {
		columnsInit();
		handleQuery();
		get_options();

	})
</script>



<style scoped>
	.avatar-uploader .avatar {
		width: 178px;
		height: 178px;
		display: block;
	}
</style>

<style>
	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}
</style>